package com.hzit.cart.interceptor;

import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
	public static ThreadLocal<String> loginThreadLocal = new ThreadLocal<>();
	//1. 在每个处理器方法前会被调用
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//1.1 得到HttpSession对象
		HttpSession session = request.getSession();
		//1.2 从session中得到login字符串
		Object login = session.getAttribute("login") ;
		if(!Objects.isNull(login)){      // 如果登录成功，就将登录用户名放到线程本地变量中并放行
			loginThreadLocal.set(login + "");
			return true;
		}
		//1.3 如果session中没有用户名，证明未登录过，就跳转到第三方登录模块进行登录
		String requestURI = request.getRequestURI();
		System.out.println("requestURI = " + requestURI);
		//1.4 构造登录成功后返回的页面地址
		String redirectUrl = "http://cart.hzit.com" + requestURI;
		//1.5 重定向到返回的地址
		response.sendRedirect("http://thirdparty.hzit.com/login?return_url=" + redirectUrl);

		return false;
	}

}
